import React from 'react';
import PropTyps from 'prop-types';
import { bindActionCreators } from './mini-redux';

export const connect = (mapStateToProps = state => state, mapDispatchToProps = {}) => (WrapComponent) => {
	return class WrapComponent extends React.Component {
		static contextProps = {
			store: PropTyps.object,
		}
		constructor(props, context) {
			super(props, context);
			this.state = {
				props: {},
			}
		}

		componentDidMount() {
			const { store } = this.context;
			// 每次redux中的状态有变化都要获取到，调用update，以便同步render到组件中
			store.subscribe(() => this.update());
			this.update();
		}

		update() {
			const { store } = this.context;
			const stateProps = mapStateToProps(store.getState());
			const dispatchProps = bindActionCreators(mapDispatchToProps, store.dispatch);
			this.setState({
				props: {
					...this.state.props,
					...stateProps,
					...dispatchProps,
				}
			});
		}

		render() {
			return <WrapComponent {...this.state.props}></WrapComponent> 
		}
	}
}

// 通过Provider将context传递到所有子孙组件中
export class Provider extends React.Component{
	static childContextTypes = {
		store: PropTyps.object,
	}
	constructor(props, context) {
		super(props, context);
		this.store = props.store;
	}
	getChildContext() {
		return {
			store: this.store,
		}
	}

	render() {
		return this.props.children;
	}
}